<template>
	<page-meta :page-style="$theme.pageStyle">
		<!-- #ifndef H5 -->
		<navigation-bar :front-color="$theme.navColor" :background-color="$theme.navBgColor" />
		<!-- #endif -->
	</page-meta>
	<view class="register bg-white min-h-full flex flex-col items-center px-[40rpx] pt-[40rpx] box-border">
		<view class="w-full">
			<view class="py-[20rpx]">身份证正面</view>
			
			<view v-if="!formData.card"><u-icon @click="chooseImg(1)" size="260" color="#999" name="photo"></u-icon></view>
			<view v-else>
				<u-image @click="chooseImg(1)" :src="formData.card" width="260" height="260"></u-image>
			</view>
			
			<view class="py-[20rpx]">身份证反面</view>
			<view v-if="!formData.card2"><u-icon @click="chooseImg(2)" size="260" color="#999" name="photo"></u-icon></view>
			<view v-else>
				<u-image @click="chooseImg(2)" :src="formData.card2" width="260" height="260"></u-image>
			</view>
			<view class="mt-[100rpx]">
				<u-button type="primary" shape="circle" @click="handleConfirm">确定</u-button>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ossImageSfz } from '@/api/app';
import { setCard } from '@/api/user';
import { useUserStore } from '@/stores/user';
import { onLoad } from '@dcloudio/uni-app';
import { reactive } from 'vue';
const userStore = useUserStore();
const formData = reactive<any>({
	card: '',
	card2: ''
});

const chooseImg = (e: any) => {
	uni.chooseImage({
		count: 1, //默认9
		sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album', 'camera'], //从相册选择
		success: function (res) {
			let files = res.tempFilePaths[0];
			uploadImageIng(files, e);
		}
	});
};

const uploadImageIng = async (file: string, num: Number) => {
	uni.showLoading({
		title: '正在上传中...'
	});
	try {
		const res: any = await ossImageSfz(file, userStore.temToken!);
		uni.hideLoading();
		if(num==1){
			formData.card = res.uri;
		}else if(num==2){
			formData.card2 = res.uri;
		}
	} catch (error) {
		uni.hideLoading();
		uni.$u.toast(error);
	}
};

const handleConfirm = async () => {
	if (!formData.card) return uni.$u.toast('请上传身份证正面');
	if (!formData.card2) return uni.$u.toast('请上传身份证反面');
	await setCard(formData);
	uni.$u.toast('操作成功');
	setTimeout(() => {
		uni.navigateBack();
	}, 1500);
};

onLoad((options) => {
	formData.card = options.card || '';
	formData.card2 = options.card2 || '';
});
</script>

<style lang="scss">
page {
	height: 100%;
}
</style>
